package it.marcomondini.proximitytools;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class AccessTableAdapter {

    public static final String KEY_ENTERING = "entering";
    public static final String KEY_TIME = "time";
    public static final String KEY_ROWID = "_id";

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String TABLE_NAME = "access";

    private final Context mCtx;

    public AccessTableAdapter(Context ctx) {
	this.mCtx = ctx;
    }

    public AccessTableAdapter open() throws SQLException {
	mDbHelper = new DatabaseHelper(mCtx);
	mDb = mDbHelper.getWritableDatabase();
	return this;
    }

    public void close() {
	mDbHelper.close();
    }

    public long createNote(boolean entering, long time) {
	ContentValues initialValues = new ContentValues();
	initialValues.put(KEY_ENTERING, entering);
	initialValues.put(KEY_TIME, time);
	return mDb.insert(TABLE_NAME, null, initialValues);
    }

    public boolean delete(long rowId) {

	return mDb.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public Cursor getAll() {

	return mDb.query(TABLE_NAME, null, null, null, null, null, null);
    }

    public Cursor get(long rowId) throws SQLException {

	Cursor mCursor = mDb.query(false, TABLE_NAME, null, KEY_ROWID + "=" + rowId, null, null, null, null, null);
	if (mCursor != null) {
	    mCursor.moveToFirst();
	}
	return mCursor;

    }

    public boolean updateNote(long rowId, boolean entering, long time) {
	ContentValues args = new ContentValues();
	args.put(KEY_ENTERING, entering);
	args.put(KEY_TIME, time);

	return mDb.update(TABLE_NAME, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}
